<template>
  <div class="min-h-200 flex-col items-center gap-y-20">
    <MyToggle v-model="active" :options="tabs" />
    <div v-show="active === 'should'">
      <MyTable
        ref="$table"
        :columns="columns"
        :get-data="(params) => projectApi.customerList({ ...params, projectId: detail.id })"
        :index="true"
        :auto-load="false"
        list-key="should_provide_list"
      ></MyTable>
      <MyDrawer ref="$form" :model-form="model" @submit="handleSubmit">
        <n-form-item
          label="资料名称"
          path="informationName"
          :rule="[{ required: true, message: '请输入资料名称！' }]"
        >
          <n-input
            v-model:value="model.informationName"
            clearable
            :maxlength="30"
            :disabled="type !== 'add'"
          />
        </n-form-item>
        <n-form-item label="资料用途" path="informationUsage">
          <n-input
            v-model:value="model.informationUsage"
            clearable
            :maxlength="100"
            :disabled="type !== 'add'"
          />
        </n-form-item>
        <n-form-item label="资料链接" path="informationLink">
          <n-input
            v-model:value="model.informationLink"
            clearable
            :maxlength="600"
            show-count
            type="textarea"
            :autosize="{
              minRows: 5,
            }"
            :disabled="type !== 'add'"
          />
        </n-form-item>
        <n-form-item label="应提供时间" path="provideTime">
          <n-date-picker
            v-model:formatted-value="model.provideTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :time-picker-props="{ format: 'HH:mm' }"
            placeholder="选择时间"
            clearable
          />
        </n-form-item>
        <n-form-item label="提供状态" path="provideStatus">
          <AsyncSelect
            v-model:value="model.provideStatus"
            label-key="name"
            value-key="dictId"
            :options="data.statusOptions"
          />
        </n-form-item>
        <n-form-item label="备注" path="notes">
          <n-input
            v-model:value="model.notes"
            clearable
            :maxlength="600"
            show-count
            type="textarea"
            :autosize="{
              minRows: 5,
            }"
          />
        </n-form-item>
      </MyDrawer>
    </div>
    <Record
      v-if="active === 'already'"
      :id="detail.id"
      :apis="customerApis"
      :permission-keys="{
        list: 'provided_list',
        add: 'provided_add',
        edit: 'provided_update',
        del: 'provided_delete',
      }"
    />
  </div>
</template>
<script setup lang="jsx">
import { useAuthTabs } from '@/hooks/useAuthTabs'
import { getSelArrDicts } from '@/api/dict'
import * as projectApi from '@/api/project'
import { useCrudPro } from '@/hooks/useCrudPro'
defineOptions({ name: 'CustomerInfo' })
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
})
const customerApis = {
  add: projectApi.customerRecordAdd,
  list: projectApi.customerRecordList,
}
const { tabs, active } = useAuthTabs([
  { label: '应提供资料', value: 'should', key: 'customer_info_should_provide' },
  { label: '已提供资料', value: 'already', key: 'customer_info_provided' },
])
const data = reactive({
  statusOptions: [],
})
const methods = reactive({
  async getStatusOptions() {
    let res = await getSelArrDicts({ codes: 'PROVIDE_STATUS' })
    data.statusOptions = res.data.PROVIDE_STATUS
  },
  handleLink(text = '') {
    const urlReg = /(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?/gi
    return text.replace(urlReg, (url) => {
      return `<a style="color: #0A56D8;" target="_blank" href=${url}>${url}</a>`
    })
  },
})
const columns = [
  {
    key: 'informationName',
    title: () => (
      <n-flex align="center">
        资料名称
        <n-button
          v-permission="should_provide_add"
          ghost
          type="primary"
          size="small"
          onClick={handleAdd}
        >
          <i class="i-material-symbols:add mr-4 text-18" />
          添加
        </n-button>
      </n-flex>
    ),
    render(row) {
      return (
        <div class="info">
          <div class="info-item">
            <div class="info-label">资料名称:</div>
            {row.informationName}
          </div>
          <div class="info-item">
            <div class="info-label">资料用途:</div>
            {row.informationUsage}
          </div>
          <div class="info-item">
            <div class="info-label">资料链接:</div>
            <div v-html={methods.handleLink(row.informationLink)}></div>
          </div>
        </div>
      )
    },
  },
  { key: 'provideTime', title: '应提供时间', render: ({ provideTime }) => $format(provideTime) },
  {
    key: 'provideStatus',
    title: '提供状态',
    render: (row) => (
      <MyStatus valueKey="dictId" options={data.statusOptions} value={row.provideStatus} />
    ),
  },
  { key: 'updateUserName', title: '更新人' },
  { key: 'updateTime', title: '更新时间', render: ({ updateTime }) => $format(updateTime) },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <n-button v-permission="should_provide_update" text onClick={() => handleEdit(row)}>
            修改
          </n-button>
          <n-button
            v-permission="should_provide_delete"
            text
            onClick={() =>
              handleDelete(row, {
                title: '删除资料',
                content: `请确定是否删除资料：${row.informationName}`,
              })
            }
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]

const { model, type, $table, $form, handleAdd, handleEdit, handleDelete, handleSubmit } =
  useCrudPro({
    name: '客户资料',
    initForm: {
      id: null,
      informationName: null,
      informationUsage: null,
      informationLink: null,
      provideTime: null,
      provideStatus: null,
      notes: null,
    },
    apis: {
      add: (params) => projectApi.customerAdd({ ...params, projectId: props.detail.id }),
      edit: projectApi.customerEdit,
      del: ({ id }) => projectApi.customerDel(id),
      info: ({ id }) => projectApi.customerInfo(id).then((res) => res.data),
    },
  })
watch(
  () => props.detail.id,
  (val) => {
    if (val) {
      nextTick(() => {
        $table.value.handleQuery()
      })
    }
  },
  {
    immediate: true,
  }
)
onBeforeMount(() => {
  methods.getStatusOptions()
})
</script>
<style lang="scss" scoped>
:deep(.n-data-table) {
  .info {
    .info-item {
      width: 200px;
      width: inherit;
      white-space: normal;
      word-break: break-all;
      word-wrap: break-word;
      .info-label {
        display: inline-block;
        font-weight: bold;
        margin-right: 6px;
      }
    }
  }
}
</style>
